package com.sunny.shop.api.v1;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.sunny.shop.core.interceptors.ScopeLevel;
import com.sunny.shop.exception.httpe.NotFoundException;
import com.sunny.shop.model.Banner;
import com.sunny.shop.service.BannerService;
import com.sunny.shop.vo.BannerItemVO;
import com.sunny.shop.vo.BannerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;

@RestController // 指明这是一个路由控制器
@RequestMapping("/banner")
@Validated // 验证注解
public class BannerController {
    @Autowired
    private BannerService bannerService;

    @Value("${sunny.oss.url}")
    private String baseUrl;

    @GetMapping("/name/{name}")
    public BannerVO getByName(@PathVariable @NotBlank String name){
        Banner banner = bannerService.getByName(name);
        if(banner == null){
            throw new NotFoundException(30005);
        }
        Mapper mapper = DozerBeanMapperBuilder.buildDefault();
        ArrayList<BannerItemVO> itemVo = new ArrayList<>();
        BannerVO bannerVO = new BannerVO();
        banner.getItems().forEach(item->{
            BannerItemVO map = mapper.map(item, BannerItemVO.class);
            map.setBannerImg(baseUrl + "/" + item.getImage().getUrl());
            map.setSongName(item.getSong().getSongName());
            map.setPlayUrl(baseUrl + "/" + item.getSong().getPlayUrl());
            map.setSongImg(baseUrl + "/" + item.getSong().getImg());
            map.setId(item.getSong().getId());
            itemVo.add(map);
        });
        bannerVO.setId(banner.getId());
        bannerVO.setName(banner.getName());
        bannerVO.setItems(itemVo);
        return bannerVO;
    }

    // @GetMapping("/test/{id}") // @PathVariable Integer id,@RequestParam String name
    @GetMapping("/test/{id}")
    @ScopeLevel
    @ResponseBody // 返回对象序列化 , @RequestBody @Validated PersonDTO person
    public String test(@PathVariable @Max(value = 3) Integer id){
        return "hello,你好";
    }
}
